<?php
require_once 'common.php';
require_once 'photosaic.php';
require_once 'database.php';

set_time_limit(0);

$photosaic = new Photosaic();
$db = new Database();

$response = $photosaic->FlickrCall('flickr.photos.getRecent');

$factor = 8;
$threshold = 20;
$prev_num = 0;
foreach ($response['photos']['photo'] as $photo_num => $photo) {

	$img_url = $photosaic->GetPhotoURL($photo, 's');

	$im = $photosaic->CreateImage($img_url);
	if ($im == null) continue;

	$colors = $photosaic->AnalyzeColors($im);

	$url = $img_url;
	$r = $colors['avg']['r'];
	$g = $colors['avg']['g'];
	$b = $colors['avg']['b'];

	$r_match = $colors['quality']['r'];
	$g_match = $colors['quality']['g'];
	$b_match = $colors['quality']['b'];

	$rgb_match = $colors['quality']['avg'];
	
	if ($rgb_match > 20) {
		$photosaic->CacheImage($db, $url,$r,$g,$b,$r_match,$g_match,$b_match,$rgb_match);
		
	}
	
	unset($rgb);
	$num_photos = mysql_fetch_row($db->query_read("select count(*) from photo_cache"));
	if (!isset($_GET['ajax']))
		if ($prev_num == $num_photos[0])
			echo	"<b style='color:#a00'>Failed</b><br/>";
		else {
			echo	"<b style='color:#0a0'>New Photo: $num_photos[0]</b><br/>";
			$prev_num = $num_photos[0];
		}
}
if (isset($_GET['ajax'])) {
	$num_photos = mysql_fetch_row($db->query_read("select count(*) from photo_cache"));
	echo	"({'photo_count' : $num_photos[0] })";
}
?>